export function formatData(data){
    let parents = data.filter(item => item.pid ===0)
    let children = data.filter(item => item.pid!= 0)
    return toDataTree(parents,children)
}

function toDataTree(parents,children){

    parents.map(p => {
        children.map((c,i) => {
            if(p.id == c.pid){
                let _children = JSON.parse(JSON.stringify(children))
                _children.splice(i,1)
                toDataTree([c],_children)
                if(p.children){
                    p.children.push(c)
                }else{
                    p.children = [c]
                }

            }
        })
    })

    return  parents;
}

export function generateRouter(data){
   return data.map(item => {
         let newItem = {
            path: item.path,
            name: item.name,
            meta:{
                right:item.right
            },
            component: ()=> import(`@/views/${item.name}`)
        }
        if(item.children&&item.children.length>0){
            newItem.redirect = { name : item.children[0].name}
            newItem.children = generateRouter(item.children)
        }
        return newItem
        
    })
}

//直接树形结构  
//  var DataTree = data.reduce((pre,next,index,arr)=>{
//     var arr1 = arr.filter(n=>n.pid ===next.id);
//     if(arr1.length){
//         next.children = arr1
//     }
//     if(next.pid===0){
//         pre.push(next)
//     }
//     return pre
// ; },[])

//  树形结构中分离出  路由结构  菜单结构一样  
//  var routeTreeData = DataTree.map(function fn(item){
//     let obj:any = {}
//     if(item.children){
//         obj.path=item.path;
//         obj.name=item.name;
//         obj.component = ()=>import(`../view/${item.name}.vue`)
//         obj.children = item.children.map((item)=>fn(item))
//         return obj;
//     }else{
//         obj.path = item.path;
//         obj.name=item.name;
//         obj.component = ()=>import(`../view/${item.name}.vue`)
//         return obj 
//     }
// })
